package com.tz.system.user.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.tz.system.user.UserUtils;
import com.tz.system.user.model.UserInfo;

public class LoginSessionFilter implements Filter {

    /** 需要排除（不拦截）的URL的正则表达式 */
    //private Pattern excepUrlPattern;
     
    /** 检查不通过时，转发的URL */
    private String forwardUrl = "/index.jsp";
    
	@Override
	public void init(FilterConfig cfg) throws ServletException {
		System.out.println("----过滤器初始化----");
		//excepUrlPattern = Pattern.compile("/index.jsp;/login/login.jsp;/system/user/login/getLogin.do");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("-----执行过滤器----");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        request.setAttribute("version", "1.1");
        String servletPath = request.getServletPath();
        /** 需要排除（不拦截）的URL的正则表达式 */
        String excepUrl = "/index.jsp;/login/login.jsp;/system/user/login/getLogin.do";
        // 如果请求的路径与forwardUrl相同，或请求的路径是排除的URL时，则直接放行
        //if (servletPath.equals(forwardUrl) || excepUrlPattern.matcher(servletPath).matches()) {
        if (servletPath.equals(forwardUrl) || excepUrl.contains(servletPath) || 
        		servletPath.lastIndexOf("css")>0 || servletPath.lastIndexOf("js")>0 ) {
            chain.doFilter(req, res);
            return;
        }
 
        UserInfo userInfo = UserUtils.getSessionUser(request);
        // 如果Session为空，则跳转到指定页面
        if (userInfo == null) {
        	System.out.println("-----用户session已失效，跳转到登录页面------");
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + StringUtils.defaultIfEmpty(forwardUrl, "/"));
        } else {
            System.out.println("-----存在用户session：" + userInfo.getUserName());
            chain.doFilter(req, res);
        }
	}

	
	@Override
	public void destroy() {
		System.out.println("----过滤器销毁----");
	}

}
